// pages/article/detail.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  
  data: {
    id:null,
    inputValue:null,
    contentDetail:{},
    comment_list: {},
    hoverClass: '',
    showDialog: false,
    focus: false,
    comment_id:0,
    inputfocus: false,
    inputhidden:false,
    surpport_array:[],
    surpport_list:[],
    maskHidden: false,
    saveHidden: false,
    shareHidden: false,
    touxiang:'',
    titleName:'',
    titleLength:0,
    canvasWidth: '',
    canvasHeight: '',
    photoDiam:100,
    infoSpace:175,
    createPosterStatus:false,
    qrcode:'../../image/erweima.jpg'

    //animationData: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let that=this;
    var title = options.title;
    var id= options.id;
    var titleLength = title.length;
    var open=wx.getStorageSync('open');
    var member_id=open.member_id;
    this.data.titleLength = titleLength;
    this.data.id=id;
    this.data.titleName=title;
    var shared=options.share;
    if(shared==undefined){
      shared=0;
    }else{
      shared=1;
    }
    if (titleLength>20){
      var barTitle=title.substring(0,16)+"...";
    }
    
    wx.setNavigationBarTitle({
      title: barTitle,
    });
    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
      success(res) {
        console.log(res)
      },
      fail(e) {
        console.log(e)
      }
    })
   this.setData({
    barTitle:barTitle,
    shared:shared
   })

   // console.log(options.title.length);
    wx.request({
      url:app.globalData.domain + 'article/index/getDetail',	//本地设置不校验合法域名
      data: { id:id,member_id:member_id},
      success: function (res) {
        console.log(res)
        that.setData({
          contentDetail: res.data.content,
          comment: res.data.comment,
         // surpport_list: res.data.surpport_list,      
         })
       
      },
      fail: function (res) {
        //wx.hideNavigationBarLoading()
       // wx.hideLoading()
       // fail()
      },
      complete: function (res) {
 
      },
    })
    wx.getSystemInfo({
      success:function(res){
        that.setData({
        screenWidth: res.screenWidth
       })
      }
    }); 
    //console.log(contentdetail)
    that.setData({
      platform:app.globalData.platform,
      open:open,
       width:app.globalData.windowWidth,
      height:app.globalData.windowHeight,
      statusBarHeight:app.globalData.statusBarHeight,
      navHeight:app.globalData.navHeight,
      marginTop:app.globalData.navTitleTop,
      domain:app.globalData.domain
    })
  },
  goBack:function(){
    wx.navigateBack();
  },
  goIndex:function(){
    wx.reLaunch({
      url: '../default/index',
    })
  },
getArtComment:function(){
  var that=this;
  var open=wx.getStorageSync('open');
  var member_id=open.member_id;
  wx.request({
   // url: 'https://lypb.com/lupao/article_comment.php',
   url:app.globalData.domain + 'article/index/getComment',
    data: { id: this.data.id,member_id:member_id},
    success:function(res){
      //console.log(res);
      that.setData({
        //contentDetail: res.data,
        comment: res.data.comment,
        //surpport_list: res.data.surpport_list,

      })
    }
  })

},
reply:function(e){
  //console.log(e);
  this.setData({
    showDialog:true,
    comment_id:e.target.dataset.commentid,
    focus: true,
    inputfocus:false,    
    inputhidden: true,
  })
  //showDialog
},

  surpSubmit:function(e){
    var comment_id=e.target.dataset.commentid;
    var surpport = e.target.dataset.surpport;
    var open=wx.getStorageSync('open');
    var member_id=open.member_id;
    var array_list=[];
    array_list= this.data.surpport_array;
    //console.log(array_list);
    //this.rotateSurpport();
    if (comment_id && !surpport){
     var that = this;
     if (array_list.indexOf(comment_id)==-1){
       this.data.surpport_array = array_list.concat(comment_id);
        wx.request({
          //url: 'https://lypb.com/lupao/comment_surpport.php',
          url:app.globalData.domain + 'article/index/commentSurpport',
          data: { member_id: member_id, comment_id: comment_id},
          success:function(res){
            console.log(res.data);
           // var returnArray=res.data;
            if (res.data.states==1){
              that.getArtComment();
             //this.getArtComment();
            }
            
          },
        })     
      }
    
  }
  
 
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let url = encodeURIComponent('/pages/article/detailid='+this.data.id+"&share=1");
    var title=this.data.titleName;
    return {
      title: title,
      path: '/pages/article/detailid='+this.data.id+"&title="+this.data.titleName+"&share=1",
     }

  
  },   
  writeTouchStart: function (event) {
    this.setData({
      hoverClass: 'write-image-hover'
    })
  },

  writeTouchEnd: function (event) {
    this.setData({
      hoverClass: ''
    })
  },
  onBindblur: function (e) {
    //console.log(e.detail.value);
  },
  closeDialog: function () {
    this.setData({
      showDialog: false,
      focus:false,
      inputfocus: false,
      inputhidden:false,
    });

  },

  commentSubmit: function (event) {
    //wx.navigateTo({
      // url: '../index/indextext=' + event.detail.value
     // url: '../index/indextext='
    //})
    var that=this;
    var comment_id=event.currentTarget.dataset.commentid;
    //var comment_id=event.target.dataset.commentid;
    if(comment_id==undefined){
      comment_id=0;
    }
    //var surpport = event.target.dataset.surpport;
    var open=wx.getStorageSync('open');
    var member_id=open.member_id;
   var id= this.data.id;
   var content=event.detail.value.comment_content;
    //console.log(event);
    if (content==""){
      wx.showToast({
        title: '请输入评论内容',
      })
    }else{

      wx.request({
       // url: 'https://lypb.com/lupao/addcomment.php',
       url:app.globalData.domain+'article/index/addComment',
        data: { member_id: member_id, id:id, comment_content:content, comment_id: comment_id},
        success:function(res){
          //console.log(res);
          var state=res.data.comment_state;
          if (state==1){
            that.setData({
              inputValue: '',
              showDialog: false,
              focus: false,
              inputhidden: false,
            })
            wx.showToast({
              title: '评论成功',
            })
            that.getArtComment();
          

          }
        },
      })
    }
  },
  createPoster: function () {
    this.setData({
      maskHidden: !this.data.maskHidden,
    });
    var that = this;
    const query=wx.createSelectorQuery()
       .select('#my')
       .fields({id:true,node:true,size:true})
       .exec((res)=>{
    //console.log(res);
          let  that=this;
          const dom = res[0]                            // 因为页面只存在一个画布，所以我们要的dom数据就是 res数组的第一个元素
          const canvas = dom.node 
          const ctx=canvas.getContext('2d');
          const dpr=wx.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr,dpr);
         // log.info("Time:"+date+"page-mine/Qrcode--createPoster--dom"+JSON.stringify(dom));
         // log.info("Time:"+date+"page-mine/Qrcode--createPoster-canvas"+JSON.stringify(canvas));
          //log.info("Time:"+date+"page-mine/Qrcode--createPoster-ctx"+JSON.stringify(ctx));
          this.setData({
            canvasDom: dom, 
            canvas:canvas,
            ctx:ctx,
            dpr: dpr 
          })
          //// 主背景画布
          wx.showLoading({ title: "生成中" }) // 显示loading
          that.canvasDraw(ctx)             // 绘制海报
            .then(function () {      
          that.canvasTitle(ctx);
          that.canvasCode(ctx).then(rrr=>{
           });
          setTimeout(function () {
            wx.canvasToTempFilePath({     //将canvas生成图片
              canvas: that.data.canvas,
              x: 0,
              y: 0,
              width: that.data.canvasWidth,
              height: that.data.canvasHeight,
              destWidth: that.data.canvasWidth*2,     //截取canvas的宽度
              destHeight: that.data.canvasHeight*2,   //截取canvas的高度
              fileType: 'png',
              quality: 1,
              success: function (res) {
                console.log('生成图片成功：', res)
                that.setData({
                  imgFilePath: res.tempFilePath,
                  createPosterStatus: true,
                })
              },
              fail: function (err){
                console.log('生成图片失败：',err)
              },
            }, this)
            wx.hideLoading()            
          }, 1000)
        }
      )
    })

  },
  canvasDraw:function(ctx) {
    //var date=util.formatTime(new Date());
    const that = this
    return new Promise(function (resolve, reject) {
      let poster = that.data.canvas.createImage();          // 创建一个图片对象
      poster.src = '../../image/bg.jpg'                     // 图片对象地址赋值
      poster.onload = () => {
        //console.log(poster.width+' '+poster.height);
       // log.info("Time:"+date+"page-mine/Qrcode--canvasDraw"+poster.width+' '+poster.height);
        that.computeCanvasSize(poster.width, poster.height) // 计算画布尺寸
          .then(function (res) {
            that.data.ctx.drawImage(poster, 0, 0, poster.width, poster.height, 0, 0, res.width, res.height);

            resolve()
          })
      }
    })
    
  },
  canvasTitle:function(ctx){
    let moy =  "长按识别二维码加入";
    var title=this.data.titleName;
    ctx.font = "normal 20px sans-serif";
    ctx.fillStyle ="rgba(128,128,128)";
    ctx.fillText(moy, 20, 140, 180);
    ctx.fillText(title, 20, 100, 710);
    
  },
  canvasCode(ctx) {
    let that=this;
    let photoDiam=this.data.photoDiam;
    //var date=util.formatTime(new Date());
    //log.info("Time:"+date+"page-mine/Qrcode--createPoster-ctx"+JSON.stringify(photoDiam));
    return new Promise(rrr=>{
      let code = this.data.canvas.createImage(); //创建img对象
      code.onload = () => {        
        let radius = photoDiam / 2                      // 圆形头像的半径
        let x = this.data.infoSpace                     // 左上角相对X轴的距离
        let y = this.data.canvasHeight - photoDiam - 20// 左上角相对Y轴的距离 ：整体高度 - 头像直径 - 微调
        this.data.ctx.save()
        this.data.ctx.arc(x + radius, y + radius, radius, 0, 2 * Math.PI) // arc方法画曲线，按照中心点坐标计算，所以要加上半径
        this.data.ctx.clip()
        this.data.ctx.drawImage(code, 0, 0, code.width, code.height, x, y, photoDiam, photoDiam) // 详见 drawImage 用法
        this.data.ctx.restore();        
       //this.data.ctx.drawImage(code,75, 260, 150, 150);

      };
      code.src =that.data.qrcode;
      setTimeout(() => {
        rrr(true)
      }, 100);
    })
  },
  computeCanvasSize:function(imgWidth, imgHeight) {
    const that = this
    return new Promise(function (resolve, reject) {
      var canvasWidth = that.data.screenWidth*2; // 获取画布宽度
      var posterHeight = that.data.screenWidth * (imgHeight / imgWidth); // 计算海报高度
      var canvasHeight = posterHeight;  // 计算画布高度 海报高度+底部高度
      that.setData({
        canvasWidth: canvasWidth,                                   // 设置画布容器宽
        canvasHeight: canvasHeight,                                 // 设置画布容器高
        posterHeight: posterHeight                                  // 设置海报高
      }, () => { // 设置成功后再返回
        that.data.canvas.width = that.data.canvasWidth * that.data.dpr // 设置画布宽
        that.data.canvas.height = canvasHeight * that.data.dpr         // 设置画布高
        that.data.ctx.scale(that.data.dpr, that.data.dpr)              // 根据像素比放大
        setTimeout(function () {
          resolve({ "width": canvasWidth, "height": posterHeight })    // 返回成功
        }, 1200)
      })
    })
  },
  savePoster:function() {
    let that=this;
        wx.saveImageToPhotosAlbum({  //保存图片到相册
          filePath: this.data.imgFilePath,
          success: function () {
            wx.showToast({
              title: "保存图片成功！",
              duration: 2000
            })
            that.setData({
              saveHideen:false
            })
          }
        })
  }, 
  onShareTimeline(){
    // console.log(e);
    var id=this.data.id
    var title=this.data.titleName;
     this.setData({
       share:true
     });
     return{
       title: title,        
            
       query: 'id='+id+'&title='+title+"&share=5",        
       //imageUrl:'https://wl.browin.net.cn/static/wechat/ad1.png'      
       }
   },
   shareLine:function(e){
     
     this.setData({
   
       share:true
     })
   },
   hiddenShare:function(){
     this.setData({
       share:false
     })
   },
  
})